using Beauty.Net.Kafka;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Beauty.NetWebApi.Controllers
{
    /// <summary>
    /// Kafka 演示控制器
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class KafkaDemoController : ControllerBase
    {
        private readonly IKafkaProducer _kafkaProducer;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="kafkaProducer">Kafka生产者实例</param>
        public KafkaDemoController(IKafkaProducer kafkaProducer)
        {
            _kafkaProducer = kafkaProducer;
        }

        /// <summary>
        /// 发送单条消息
        /// </summary>
        /// <param name="topic">主题名称</param>
        /// <param name="request">消息请求</param>
        /// <returns>发送结果</returns>
        [HttpPost("produce")]
        public async Task<IActionResult> ProduceMessage([FromQuery] string topic, [FromBody] KafkaMessageRequest request)
        {
            if (string.IsNullOrEmpty(topic))
            {
                return BadRequest("Topic cannot be empty");
            }

            if (request == null || string.IsNullOrEmpty(request.Value))
            {
                return BadRequest("Message value cannot be empty");
            }

            // 创建消息对象
            var message = new KafkaMessage
            {
                Key = request.Key ?? string.Empty,
                Value = request.Value ?? string.Empty,
                Headers = request.Headers ?? new Dictionary<string, object>()
            };

            // 发送消息
            var result = await _kafkaProducer.ProduceAsync(topic, message);

            return Ok(new
            {
                Success = result.IsSuccess,
                Message = result.IsSuccess ? "Message sent successfully" : "Failed to send message",
                Topic = result.Topic,
                Partition = result.Partition,
                Offset = result.Offset,
                Error = result.Error
            });
        }

        /// <summary>
        /// 批量发送消息
        /// </summary>
        /// <param name="topic">主题名称</param>
        /// <param name="requests">消息请求列表</param>
        /// <returns>发送结果列表</returns>
        [HttpPost("produce-batch")]
        public async Task<IActionResult> ProduceBatch([FromQuery] string topic, [FromBody] List<KafkaMessageRequest> requests)
        {
            if (string.IsNullOrEmpty(topic))
            {
                return BadRequest("Topic cannot be empty");
            }

            if (requests == null || requests.Count == 0)
            {
                return BadRequest("Messages cannot be empty");
            }

            // 转换为Kafka消息对象列表
            var messages = new List<IKafkaMessage>();
            foreach (var request in requests)
            {
                if (!string.IsNullOrEmpty(request.Value))
                {
                    messages.Add(new KafkaMessage
                    {
                        Key = request.Key ?? string.Empty,
                        Value = request.Value ?? string.Empty,
                        Headers = request.Headers ?? new Dictionary<string, object>()
                    });
                }
            }

            // 批量发送消息
            var results = await _kafkaProducer.ProduceBatchAsync(topic, messages);

            return Ok(new
            {
                Success = true,
                Count = results.Count(),
                Results = results.Select(r => new
                {
                    Topic = r.Topic,
                    Partition = r.Partition,
                    Offset = r.Offset,
                    Key = r.Key,
                    IsSuccess = r.IsSuccess,
                    Error = r.Error
                })
            });
        }

        /// <summary>
        /// 事务发送消息
        /// </summary>
        /// <param name="topic">主题名称</param>
        /// <param name="requests">消息请求列表</param>
        /// <returns>发送结果列表</returns>
        [HttpPost("produce-transaction")]
        public async Task<IActionResult> ProduceTransaction([FromQuery] string topic, [FromBody] List<KafkaMessageRequest> requests)
        {
            if (string.IsNullOrEmpty(topic))
            {
                return BadRequest("Topic cannot be empty");
            }

            if (requests == null || requests.Count == 0)
            {
                return BadRequest("Messages cannot be empty");
            }

            // 转换为Kafka消息对象列表
            var messages = new List<IKafkaMessage>();
            foreach (var request in requests)
            {
                if (!string.IsNullOrEmpty(request.Value))
                {
                    messages.Add(new KafkaMessage
                    {
                        Key = request.Key ?? string.Empty,
                        Value = request.Value ?? string.Empty,
                        Headers = request.Headers ?? new Dictionary<string, object>()
                    });
                }
            }

            try
            {
                // 事务发送消息
                var results = await _kafkaProducer.ProduceTransactionAsync(topic, messages);

                return Ok(new
                {
                    Success = true,
                    Count = results.Count(),
                    Message = "Transaction committed successfully",
                    Results = results.Select(r => new
                    {
                        Topic = r.Topic,
                        Partition = r.Partition,
                        Offset = r.Offset,
                        Key = r.Key,
                        IsSuccess = r.IsSuccess,
                        Error = r.Error
                    })
                });
            }
            catch (System.Exception ex)
            {
                return StatusCode(500, new
                {
                    Success = false,
                    Message = "Transaction failed",
                    Error = ex.Message
                });
            }
        }
    }

}